package com.netx.generics.basic;
import java.io.Writer;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.Iterator;
import com.netx.generics.util.Strings;


public class ErrorListPrinter {

	private final PrintWriter _out;
	private int _messageIndentLength = 3;
	
	public ErrorListPrinter(Writer out) {
		Checker.checkNull(out, "out");
		if(out instanceof PrintWriter) {
			_out = (PrintWriter)out;
		}
		else {
			_out = new PrintWriter(out);
		}
	}

	public ErrorListPrinter(OutputStream out) {
		Checker.checkNull(out, "out");
		_out = new PrintWriter(out);
	}
	
	public int getMessageIndentLength() {
		return _messageIndentLength;
	}

	public void setMessageIndentLength(int messageIndentLength) {
		Checker.checkMinValue(messageIndentLength, 0, "messageIndentLength");
		_messageIndentLength = messageIndentLength;
	}
	
	public void print(ErrorList el) {
		Checker.checkNull(el, "el");
		List<String> errors = el.getErrors();
		if(errors != null) {
			String eh = el.getErrorsHeader();
			_out.print(eh);
			_out.println(eh.endsWith(":") ? "" : ":");
			_printMessages(errors);
		}
		List<String> warnings = el.getWarnings();
		if(warnings != null) {
			String wh = el.getWarningsHeader();
			_out.print(wh);
			_out.println(wh.endsWith(":") ? "" : ":");
			_printMessages(warnings);
		}
		_out.flush();
	}

	private void _printMessages(List<String> messages) {
		Iterator<String> it = messages.iterator();
		while(it.hasNext()) {
			if(_messageIndentLength > 0) {
				_out.print(Strings.repeat(" ", _messageIndentLength));
			}
			_out.println(it.next());
		}
	}
}
